package server.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import server.demo.entity.User;
import server.demo.repository.UserRepository;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }
    
    public Optional<User> getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public User createUser(User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在: " + user.getUsername());
        }
        
        if (userRepository.existsByIdCard(user.getIdCard())) {
            throw new RuntimeException("身份证号已存在: " + user.getIdCard());
        }
        
        // 简化处理，直接保存密码（实际项目中需要加密）
        return userRepository.save(user);
    }
    
    public User updateUser(Long id, User user) {
        Optional<User> existingUser = userRepository.findById(id);
        if (existingUser.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        User toUpdate = existingUser.get();
        
        // 检查用户名是否冲突
        if (!toUpdate.getUsername().equals(user.getUsername()) && 
            userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在: " + user.getUsername());
        }
        
        // 检查身份证号是否冲突
        if (!toUpdate.getIdCard().equals(user.getIdCard()) && 
            userRepository.existsByIdCard(user.getIdCard())) {
            throw new RuntimeException("身份证号已存在: " + user.getIdCard());
        }
        
        toUpdate.setUsername(user.getUsername());
        toUpdate.setRealName(user.getRealName());
        toUpdate.setPhone(user.getPhone());
        toUpdate.setIdCard(user.getIdCard());
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            toUpdate.setPassword(user.getPassword());
        }
        
        return userRepository.save(toUpdate);
    }
    
    public void deleteUser(Long id) {
        if (!userRepository.existsById(id)) {
            throw new RuntimeException("用户不存在");
        }
        userRepository.deleteById(id);
    }
    
    // 简化的登录验证（实际项目中需要密码加密验证）
    public Optional<User> login(String username, String password) {
        Optional<User> user = userRepository.findByUsername(username);
        if (user.isPresent() && user.get().getPassword().equals(password)) {
            return user;
        }
        return Optional.empty();
    }
}